;(function () {
  var REGISTER_FIELD = 'phone' // 分享理解的参数
  var COUNT_NUMBER = 120 // 可再次获得验证码的倒计时
  var authCodeFlag = false, // 验证码获得凭证
      dialogST = null, // 提示消失ST
      sharerInfo = {}, // 初始化获得的分享者信息 
      isSubmitFlag = false // 是否可发起提交的凭证

  authBtnHandle()
  phoneHandle()
  passwardHandle()
  submitHandle()
  init()

  // 获得推荐人初始信息
  function init() {
    $.ajax({
      type: 'post',
      url: '/share/register',
      data: {
        loginAccount: getUrlParam(REGISTER_FIELD)
      },
      success: function(res) {
        if (res.code == '1000') {
          sharerInfo = res.data || {}
          if (sharerInfo.userType == '1') $('.logo').attr('src', './img/c_logo180.png')
          $('.recommend-input').val(sharerInfo.userNickname || sharerInfo.loginAccount || '')
        }
      },
      dataType: 'json',
      error: function(e) {
        dialog('服务器正忙...' + e)
      }
    })
  }

  // 提交事件
  function submitHandle() {
    $('.submit').on('click', function () {
      var phone = checkPhoneNumber()
      if (!phone) return
      
      var password = checkPassword()
      if (!password) return
      
      var authCode = checkAuthCode()
      if (!password) return

      if (!sharerInfo) return

      submitIt({
        loginAccount: phone,
        smsMessageCode: authCode,
        loginPassword: password,
        userType: sharerInfo.userType || '',
        shareRegisterUserId: sharerInfo.userId || 0,
        sourceFrom: 'web'
      })
    })
  }

  // 发起提交
  function submitIt(params) {
    if (isSubmitFlag) return
    isSubmitFlag = true

    $.ajax({
      type: 'post',
      url: '/user/nonlogin/register',
      data: params,
      success: function(res) {
        if (res.code == '1000') {
          dialog('注册成功, 即将跳转下载')
          setTimeout(function() {
            window.location.href = './download'
          }, 1500)
        } else {
          dialog(res.msg)
        }
      },
      dataType: 'json',
      error: function(e) {
        dialog('服务器正忙...')
      },
      complete: function() {
        isSubmitFlag = false
      }
    })
  }

  // 手机号码监听
  function phoneHandle() {
    var $phone = $('.phone-input')
    $phone.on('blur', function () {
      checkPhoneNumber()
    })
  }

  // 密码输入框监听
  function passwardHandle() {
    var $passwordInput = $('.password-input'),
        passwordInput = $passwordInput.get(0)

    $(document).on('click', '.show-hidden', function () {
      if ($(this).hasClass('hidden-password')) {
        $(this).removeClass('hidden-password').addClass('show-password')
        passwordInput.type = 'text'
      } else {
        $(this).removeClass('show-password').addClass('hidden-password')
        passwordInput.type = 'password'
      }
      $('.password-input').focus()
    })

    $passwordInput.on('blur', function() { checkPassword() })
  }

  // 验证码监听
  function authBtnHandle() {
    $('.auth-code-btn').on('click', function () {
      var phone = checkPhoneNumber()
      if (phone) {
        if (!authCodeFlag) {
          authCodeFlag = true
          getAuthCode(phone)
          $('.code-input').focus()
        } else {
          dialog('验证码还有效，请勿多次发送')
        }
      }
    })
  }

  // 获取验证码间隔
  function countdown() {
    var $btn = $('.auth-code-btn'),
        count = COUNT_NUMBER

    function fn() {
      $btn.html(count + 's')
      if (count > 0) {
        --count
        setTimeout(function () {
          fn()
        }, 1000)
      } else {
        authCodeFlag = false
        $btn.html('重新获得')
      }
    }

    fn()
  }

  // 获得 url参数
  function getUrlParam(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(r[2])
    return null
  }

  // 检查验证码是否合规
  function checkAuthCode() {
    var authCode = $('.code-input').val()
    if (authCode.length != 4) 
      return false
    return authCode
  }

  // 发起验证码请求
  function getAuthCode(phone) {
    $.ajax({
      type: 'get',
      url: '/send/code/' + phone,
      success: function(res) {
        countdown()
        if (res.code == '1000') {
          dialog('验证码已发送，请注意查收')
        } else {
          dialog(res.msg)
        }
      },
      dataType: 'json',
      error: function(e) {
        dialog('服务器正忙...')
      }
    })
  }

  // 提示信息
  function dialog(msg) {
    var $error = $('.error')
    $error.html(msg).slideDown()
    clearTimeout(dialogST)
    dialogST = setTimeout(function () { $error.stop().slideUp() }, 1500)
  }

  // 检查手机号码格式
  function checkPhoneNumber() {
    var reg = /^1[0-9]{10}$/,
        phone = $('.phone-input').val()
    if (reg.test(phone)) return phone
    dialog('手机号码错误')
    return false
  }

  // 检查密码是否合规
  function checkPassword() {
    var password = getPassword($('.password-input').val())

    if (password.length < 6 || password.length > 16) {
      dialog('密码长度应为6~16位...')
      return false
    }
    return password
  }

  // 获得密码，中文会被清掉
  function getPassword() { 
    var val = document.querySelector('.password-input').value,
        temp = '' 
    for (var i = 0; i < val.length; i++) 
      if(val.charCodeAt(i) > 0 && val.charCodeAt(i) < 255) 
        temp += val.charAt(i) 
    return temp 
  } 
})()